﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;

namespace KC.Business.Stockmaster
{
	public static class JsonLookups
	{
		// GET calls
		private static readonly string
			ApiKey = @"2b027dc354c8286e7783c1d370ae342afa212c6c4487f2d5c2",
			ProfileInfoURL = @"https://api.empireavenue.com/profile/info?apikey={0}&username={1}&password={2}&ticker={3}",
			NewUserURL = @"https://api.empireavenue.com/search/recent?apikey={0}&username={1}&password={2}",
			BalanceURL = @"https://api.empireavenue.com/profile/bank/balance?apikey={0}&username={1}&password={2}",
			CommissionUrl = @"https://api.empireavenue.com/shares/commission/get?apikey={0}&username={1}&password={2}&ticker={3}",
			HistorySharesBoughtUrl = @"https://api.empireavenue.com/history/shares/bought?apikey={0}&username={1}&password={2}&ticker={3}";

		public static string ProfileInfo(string username, string password, string ticker) {
			return new WebClient().DownloadString(string.Format(ProfileInfoURL, new object[] { ApiKey, username, HttpUtility.UrlEncode(password), ticker }));
		}
		public static string NewStocks(string username, string password)
		{
            string url = string.Format(NewUserURL, ApiKey, username, HttpUtility.UrlEncode(password));
            try { return new WebClient().DownloadString(url); }
            catch (WebException ex)
            {
                throw new ApplicationException("Error looking up new stocks. Tried to download URL: " +
                    url.Replace(ApiKey, "{APIKEY}").Replace(HttpUtility.UrlEncode(password), "{PASSWORD}"),
                    ex);
            }
		}
		public static string Balance(string username, string password)
		{
            return new WebClient().DownloadString(string.Format(BalanceURL, ApiKey, username, HttpUtility.UrlEncode(password)));
		}
		public static string Commission(string username, string password, string ticker)
		{
			return new WebClient().DownloadString(string.Format(CommissionUrl, new object[] { ApiKey, username, HttpUtility.UrlEncode(password), ticker }));
		}
		
		/// <summary>Given a list of tickers, returns only the ones the user has never bought</summary>
		/// <param name="username">user name</param>
		/// <param name="password">password</param>
		/// <param name="tickers">List of tickers</param>
		/// <returns>List of tickers the user has never bought</returns>
		public static List<string> FilterStocksByOwned(string username, string password, List<string> tickers)
		{
            if (tickers == null || tickers.Count == 0) return new List<string>();
			List<string> returnList = new List<string>();
			foreach (string ticker in tickers)
			{
				string strResult = new WebClient().DownloadString(string.Format(HistorySharesBoughtUrl, new string[] { ApiKey, username, HttpUtility.UrlEncode(password), ticker }));
				if (strResult.Contains("Does not own"))
					returnList.Add(ticker);
				if (returnList.Count >= 20) 
					break;
			}

			return returnList;
		}

		public static Dictionary<string, dynamic> DeserializeJson(string JsonString)
		{
			return JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(JsonString);
		}
		
	}

	public static class JsonPosts
	{
		// POST calls
		private static readonly string
			ApiKey = @"2b027dc354c8286e7783c1d370ae342afa212c6c4487f2d5c2",
			BuyURL = @"https://api.empireavenue.com/shares/buy",
			BuyURLPostData = "apikey={0}&username={1}&password={2}&ticker={3}&shares={4}&last_trade={5}";
		public static string Buy(string username, string password, string ticker, int shares, double last_trade)
		{
			WebClient client = new WebClient();
			System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();
			nvc.Add("ticker", ticker);
			nvc.Add("shares", shares.ToString());
			nvc.Add("last_trade", last_trade.ToString());
			byte[] bytes = client.UploadValues(string.Format(BuyURL + "?" + BuyURLPostData, new object[] { ApiKey, username, HttpUtility.UrlEncode(password), ticker, shares, last_trade }), "POST", nvc);
			return System.Text.Encoding.ASCII.GetString(bytes);
		}

		public static Dictionary<string, dynamic> DeserializeJson(string JsonString)
		{
			return JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(JsonString);
		}
	}

	/*
	{"meta":{"total_rows":1,"uri":"\/profile\/info","limit":150,"limit_type":"user","requests":1,"reset":3600,"recorded":"2011-05-03 22:40:30"},
	"data":[{"ticker":"TSILB","first_name":"Kevin","last_name":"Connolly","full_name":"Kevin Connolly","site_name":"","site_url":"","country":"United States","location":"Colorado Springs, CO","joined":"2011-04-06 20:39:28",
		"type":"person","max_shares":"200","commission":"5.00","last_trade":"27.94915","outstanding_shares":"1476","total_shares":"10000","close":"26.90643","close_money":"17.55664","open":"27.24715","yesterday_lowest":"26.90643",
		"yesterday_change":"0.19676","yesterday_highest":"26.90643","volume":"0","market_last_close":"2011-05-03 10:21:37","market_last_open":"2011-05-03 10:21:37","current_status":"Mwuhahahahaha!","current_status_set":"2011-04-14 21:31:43",
		"trading_status":"enabled","sm_portrait":"http:\/\/www.empireavenue.com\/public\/portraits\/p_sm_TSILB_a4f667cf151b.jpg","lg_portrait":"http:\/\/www.empireavenue.com\/public\/portraits\/p_lg_TSILB_a4f667cf151b.jpg","investments_count":"5",
		"shareholders_count":"8","thumbs_up_count":"0","thumbs_down_count":"0","shares_owned_count":"608","listed_count":"3","recommended_count":"0","held_shares":0}]}
	*/

	namespace Twitter
	{
		public static class JsonLookups
		{
			private static readonly string SearchURL = @"http://search.twitter.com/search.json?q={0}",
				ConsumerSecret = @"GOMXAyinGXfiIHojGy0LXmMPh6wr48wqyyWs1ZZf8O0";

			public static string Search(string query)
			{
				return new WebClient().DownloadString(string.Format(SearchURL, HttpUtility.UrlEncode(query)));
			}
			public static string Search(string firstname, string lastname, string city)
			{
				// full_name, country, location, ticker, last_trade, created
				// full_name: first last
				// location: city // city, state // ". (null)" // ""
				return new WebClient().DownloadString(string.Format(SearchURL, HttpUtility.UrlEncode("")));
			}

			public static string GetTwitterRequestToken()
			{
				TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
				string 
					oauth_timestamp = Convert.ToInt64(ts.TotalSeconds).ToString(),
					oauth_nonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));

				//string RequestTokenUrl = @"http://api.twitter.com/oauth/request_token?oauth_consumer_key=" + ConsumerSecret + "&oauth_signature_method=&oauth_signature=&oauth_timestamp=&oauth_nonce=&oauth_version=1.0";
				string RequestTokenUrl = "POST&" + Uri.EscapeDataString("https://api.twitter.com/oauth/request_token")
					+ "&oauth_consumer_key%3D" + ConsumerSecret
					+ "%26" + "oauth_nonce%3D" + oauth_nonce
					+ "%26" + "oauth_signature_method%3DHMAC-SHA1"
					+ "%26" + "oauth_timestamp%3D" + oauth_timestamp
					+ "%26" + "oauth_version%3D1.0";

				// Exchange request token for Access token
				//byte[] data = new WebClient().DownloadData(RequestTokenUrl);
				System.Net.ServicePointManager.Expect100Continue = false;
				//string data = new WebClient().UploadString(@"http://api.twitter.com/oauth/request_token", RequestTokenUrl);

				

				//string requestToken = Encoding.UTF8.GetString(data);
				//bool found = false;
				//string[] words = requestToken.Split('&');
				//for (uint L = 0; L < words.Length; L++) {
				//        if (words[L].StartsWith("oauth_token=")) {
				//                found = true;
				//                requestToken = words[L];
				//                break; } }
				//if (!found) 
				//        throw new Exception("Unknown response from Twitter server");


				//var sigBase = "GET&" + Uri.EscapeDataString("https://api.twitter.com/oauth/access_token") + "&" + Uri.EscapeDataString("oauth_consumer_key=" + ConsumerSecret)
				//    + "%26" + Uri.EscapeDataString("oauth_nonce=" + oauth_nonce)
				//    + "%26" + Uri.EscapeDataString("oauth_signature_method=HMAC-SHA1")
				//    + "%26" + Uri.EscapeDataString("oauth_timestamp=" + oauth_timestamp)
				//    + "%26" + Uri.EscapeDataString("oauth_token=" + page.Request.QueryString["oauth_token"])
				//    + "%26" + Uri.EscapeDataString("oauth_version=1.0");
				//string signature = createSignature(sigBase);


				//http://twitter.com/oauth/request_token
				//	?oauth_consumer_key=tViV8vAt4cqSKbGdPGWT7Q
				//	&oauth_nonce=2790042
				//	&oauth_signature_method=HMAC-SHA1
				//	&oauth_timestamp=1244567068
				//	&oauth_version=1.0
				//	&oauth_signature=KzxcXN%2bQ0AJoAJ%2flQfzs8SLjC%2fQ%3d

				//GS - Remove the trailing ambersand char, remember
				//it's been urlEncoded so you have to remove the
				//last 3 chars - %26
				//baseString = baseString.Substring(0, baseString.Length - 3);
					return null;

			}
			/// <summary>Creates the signature that oAuth wants, because oAuth is gay</summary>
			/// <param name="signatureBase"></param>
			/// <param name="tokenSecret">oauth_token from oAuth provider</param>
			/// <returns>Valid oAuth request signature string</returns>
			private static string createSignature(string signatureBase, string tokenSecret) {
				string key = ConsumerSecret + "&" + tokenSecret;
				var keyBytes = Encoding.UTF8.GetBytes(key);
				var sigMethod = new System.Security.Cryptography.HMACSHA1(keyBytes);
				byte[] data = Encoding.UTF8.GetBytes(signatureBase);
				var hash = sigMethod.ComputeHash(data);
				var sig = Convert.ToBase64String(hash);
				sig = Uri.EscapeDataString(sig);
				return sig;
			}
			

		}
	}
}